package com.edu.edu.day25_homework.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;

import com.edu.edu.day25_homework.Contans;
import com.edu.edu.day25_homework.adapter.MoviesAdapter;
import com.edu.edu.day25_homework.R;
import com.edu.edu.day25_homework.activity.PlayVideoActivity;
import com.edu.edu.day25_homework.bean.Movies;
import com.edu.edu.day25_homework.thread.loadJsonTask;

import java.util.ArrayList;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 */
public class MovieFragment extends Fragment implements loadJsonTask.onGetJsonResultListener {


    private ListView mLv;
    private ViewPager mVp;
    private List<ImageView> images;
    private MoviesAdapter adapter;

    //处理消息
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                int index = msg.arg1;
                mVp.setCurrentItem(index);
            }
        }
    };

    public MovieFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_movie, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mLv = (ListView)view.findViewById(R.id.movie_list);
        mVp = (ViewPager)view.findViewById(R.id.movie_vp);

        initViewData();

        initListData();
    }

    private void initListData() {

        new loadJsonTask(this).execute(Contans.JSON_ISSHOW);

        assert mLv != null;

        adapter = new MoviesAdapter(getActivity());

        mLv.setAdapter(adapter);

        mLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long l) {

                Movies movie = (Movies) adapter.getItem(position);
                Intent intent = new Intent(getActivity(),PlayVideoActivity.class);
                intent.putExtra("data",movie);
                Log.d("TAG","moviefragment>>>>>>>>>>" + movie.getMobliepreview());
                startActivity(intent);
            }
        });
    }
    @Override
    public void onGetJsonResult(List<Movies> result) {
        adapter.setData(result);

    }

    private void initViewData() {
        images = new ArrayList<>();
        int[] imagesId = getImagesId();
        for (int i = 0; i < imagesId.length; i++) {
            ImageView image = new ImageView(getActivity());
            image.setBackgroundResource(imagesId[i]);
            images.add(image);
        }

        mVp.setCurrentItem(0);
        assert mVp != null;
        mVp.setAdapter(new MyMovieAdapter());
        assert mVp != null;
        mVp.setCurrentItem(100);

        mVp.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
        });
        //开启线程
        final AutoRunThread mTask = new AutoRunThread();
        mTask.startRun();

        //处理ViewPager的触摸事件
        mVp.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN://按下事件,停止自动轮播
                        mTask.stopRun();
                        break;
                    case MotionEvent.ACTION_CANCEL://取消和抬起事件,开始自动轮播
                    case MotionEvent.ACTION_UP:
                        mTask.startRun();
                        break;
                }
                return false;
            }
        });
    }
    class MyMovieAdapter extends PagerAdapter{

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(images.get(position  % images.size()));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(images.get(position % images.size()));
            return images.get(position % images.size());
        }
    }

    public int[] getImagesId() {
        return new int[]{R.mipmap.image06,R.mipmap.image07,R.mipmap.image08};
    }
    //实现广告轮播的自动切换效果
    class AutoRunThread implements Runnable {

        private long delayTime = 4000;
        //任务是否开始
        private boolean isStart = false;

        //开始任务
        public void startRun() {
            if (!isStart) {
                //清除本次任务之前的所有其他任务
                mHandler.removeCallbacks(this);
                isStart = true;
                mHandler.postDelayed(this, delayTime);
            }
        }

        //停止任务
        public void stopRun() {
            if (isStart) {
                isStart = false;
                mHandler.removeCallbacks(this);
            }
        }

        @Override
        public void run() {

            //获取当前页面的索引值
            int currentItem = mVp.getCurrentItem();
            Message msg = Message.obtain();
            msg.what = 1;
            msg.arg1 = ++currentItem;
            mHandler.sendMessage(msg);

            //mHandler.sendMessageDelayed();
            //递归...
            mHandler.postDelayed(this, delayTime);
        }
    }
}
